package com.example.campus.api_controller.shiro;


import com.example.campus.dao.model.shiro.Permission;
import com.example.campus.dao.model.shiro.Role;
import com.example.campus.dao.table_gateway.shiro.RoleMapper;
import com.example.campus.page_controller.dto.ResponseResult;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

import static com.example.campus.common.BusinessConstants.ADMIN_API_BASE;

@RestController
@RequestMapping(ADMIN_API_BASE + "/roles")
public class RoleController {
    @Autowired
    RoleMapper roleMapper;

    @PostMapping
    public ResponseResult<String> addRole(@RequestBody Role role) {
        roleMapper.addRole(role);

        return ResponseResult.ok();
    }

    @GetMapping
    public ResponseResult<Set<Role>> getAllRoles() {
        var roles = roleMapper.getAllRoles();
         return ResponseResult.ok(roles);
    }

    @GetMapping("{id}")
    public  ResponseResult<Role> getRoleById(@PathVariable("id")long id){
        var role = roleMapper.getRoleById(id);
        return ResponseResult.ok(role);
    }

    @PutMapping
    public ResponseResult<String> updateRoleById(@Valid @RequestBody Role role) {
        roleMapper.updateRoleById(role);

        return ResponseResult.ok();
    }

    @DeleteMapping("{id}")
    public ResponseResult<String> deleteRoleById(@PathVariable("id")long id){
        roleMapper.deleteRoleById(id);
        return ResponseResult.ok();
    }

    @GetMapping("/{id}/perms")
    public  ResponseResult<Set<Permission>> getPermissionsOfRoleByRoleId(@PathVariable("id")long id){
        var role = roleMapper.getRoleWithPermissionsByRoleId(id);
        return ResponseResult.ok(role.getPermissions());
    }
}
